<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox, ElPagination, ElTable, ElTableColumn, ElInput, ElButton, ElDialog, ElForm, ElFormItem, ElSelect, ElOption, ElDatePicker } from 'element-plus'
import { roleApi } from '@/api/role.js'

// 表格数据
const tableData = ref([])
const total = ref(0)
const loading = ref(false)

// 分页参数
const page = ref(1)
const pageSize = ref(10)

// 搜索参数
const searchForm = reactive({
  name: ''
})

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formData = reactive({
  id: '',
  name: '',
  label: '',
  remark: ''
})
const formRef = ref(null)

// 获取角色列表
const getRoleList = async () => {
  loading.value = true
  try {
    const params = {
      page: page.value,
      pageSize: pageSize.value,
      name: searchForm.name
    }
    const res = await roleApi.getRoleList(params)
    if (res && res.data && res.data.code === 1) {
      tableData.value = res.data.data.rows
      total.value = res.data.data.total
    } else {
      ElMessage.error(res?.data?.msg || '获取角色列表失败')
    }
  } catch (error) {
    ElMessage.error('获取角色列表失败')
    console.error('获取角色列表失败:', error)
    // 处理401未授权错误
    if (error.response && error.response.status === 401) {
      ElMessage.error('登录已过期，请重新登录')
      console.error('401未授权，需要重新登录')
    }
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  page.value = 1
  getRoleList()
}

// 重置搜索
const handleReset = () => {
  searchForm.name = ''
  page.value = 1
  getRoleList()
}

// 打开添加对话框
const openAddDialog = () => {
  dialogTitle.value = '添加角色'
  // 重置表单数据
  formData.id = ''
  formData.name = ''
  formData.label = ''
  formData.remark = ''
  dialogVisible.value = true
  // 重置表单验证
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

// 打开编辑对话框
const openEditDialog = async (row) => {
  try {
    const res = await roleApi.getRoleDetail(row.id)
    if (res && res.data && res.data.code === 1) {
      dialogTitle.value = '修改角色'
      // 设置表单数据
      formData.id = res.data.data.id
      formData.name = res.data.data.name
      formData.label = res.data.data.label
      formData.remark = res.data.data.remark
      dialogVisible.value = true
    } else {
      ElMessage.error(res?.data?.msg || '获取角色详情失败')
    }
  } catch (error) {
    ElMessage.error('获取角色详情失败')
    console.error('获取角色详情失败:', error)
  }
}

// 删除角色
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除角色「${row.name}」吗？`, '删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await roleApi.deleteRole(row.id)
      if (res && res.data && res.data.code === 1) {
        ElMessage.success('删除成功')
        getRoleList()
      } else {
        ElMessage.error(res?.data?.msg || '删除失败')
      }
    } catch (error) {
      ElMessage.error('删除失败')
      console.error('删除角色失败:', error)
    }
  }).catch(() => {
    // 用户取消删除
  })
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    // 判断是添加还是修改
    const isEdit = !!formData.id
    const apiMethod = isEdit ? roleApi.updateRole : roleApi.addRole
    
    // 调整数据结构，确保与后端RoleDO类格式匹配
    // 后端BeanUtil.hasNullField检查除了"remark", "page", "pageSize","createTime","updateTime"外的所有字段
    // 所以需要确保其他必要字段都有值，不能为null
    const data = isEdit ? {
      id: Number(formData.id), // 确保id是数字类型
      name: formData.name || '', // 确保不为null
      label: formData.label || '', // 确保不为null
      // remark可以为null，不需要默认值
      remark: formData.remark, 
      // 确保所有其他可能的必填字段都有值
      delFlag: formData.delFlag !== undefined ? formData.delFlag : 0, // 删除标记，默认为0
      // createTime和updateTime会被排除检查，设置为null即可
      createTime: null,
      updateTime: null
    } : {
      name: formData.name || '', // 确保不为null
      label: formData.label || '', // 确保不为null
      // remark可以为null，不需要默认值
      remark: formData.remark,
      // 确保所有其他可能的必填字段都有值
      delFlag: 0, // 新增时默认为0
      // createTime和updateTime会被排除检查，设置为null即可
      createTime: null,
      updateTime: null
    }
    
    console.log('提交数据:', data, '操作类型:', isEdit ? '修改' : '添加')
    
    const res = await apiMethod(data)
    if (res && res.data && res.data.code === 1) {
      ElMessage.success(isEdit ? '修改成功' : '添加成功')
      dialogVisible.value = false
      getRoleList()
    } else {
      const errorMsg = res?.data?.msg || (isEdit ? '修改失败' : '添加失败')
      ElMessage.error(errorMsg)
      console.warn('操作返回非成功状态:', errorMsg)
    }
  } catch (error) {
    if (error.name !== 'Error') {
      // 表单验证失败
      return
    }
    ElMessage.error('操作失败')
    console.error('提交表单失败:', error)
    // 显示更详细的错误信息
    if (error.response && error.response.data && error.response.data.msg) {
      ElMessage.error(`错误: ${error.response.data.msg}`)
      console.error('响应错误详情:', error.response.data)
    }
    // 处理401未授权错误
    if (error.response && error.response.status === 401) {
      ElMessage.error('登录已过期，请重新登录')
      console.error('401未授权，需要重新登录')
    }
  }
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  getRoleList()
}

const handleCurrentChange = (val) => {
  page.value = val
  getRoleList()
}



// 格式化时间
const formatDate = (date) => {
  if (!date) return ''
  return new Date(date).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 组件挂载时获取数据
onMounted(() => {
  getRoleList()
})
</script>

<template>
  <div class="dept-management">
    <!-- 搜索区域 -->
    <div class="search-area">
      <el-row :gutter="12">
        <el-col :span="6">
          <el-form-item label="角色名称:">
            <el-input 
              v-model="searchForm.name" 
              placeholder="请输入角色名称"
              clearable
              style="width: 100%"
            />
          </el-form-item>
        </el-col>

        <el-col :span="4" :offset="14" class="button-col">
          <el-button type="primary" @click="handleSearch" style="margin-right: 8px;">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-col>
      </el-row>
      
      <!-- 分隔符 -->
      <div class="divider"></div>
      
      <!-- 添加角色按钮 -->
      <div class="action-area">
        <el-button type="primary" @click="openAddDialog">添加角色</el-button>
      </div>
    </div>

    <!-- 数据表格 -->
    <el-table 
      :data="tableData" 
      style="width: 100%"
      stripe
      border
      v-loading="loading"
      element-loading-text="加载中..."
    >
        <el-table-column type="index" label="序号" width="80" align="center"></el-table-column>
        <el-table-column prop="name" label="角色名称" align="center" min-width="160"></el-table-column>
        <el-table-column prop="label" label="角色标识" align="center" min-width="160"></el-table-column>
        
        <el-table-column prop="updateTime" label="最后修改时间" align="center" min-width="180">
          <template #default="{ row }">
            {{ formatDate(row.updateTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="{ row }">
            <el-button 
              type="primary" 
              link 
              @click="openEditDialog(row)"
              style="margin-right: 8px;"
            >
              修改
            </el-button>
            <el-button type="danger" link @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

    <!-- 分页控件 -->
    <div class="pagination-area">
      <el-pagination
        v-model:current-page="page"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, prev, pager, next, jumper, sizes"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加/修改角色对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      destroy-on-close
    >
      <el-form
        ref="formRef"
        :model="formData"
        label-width="100px"
        :label-position="'top'"
      >
        <el-form-item label="角色名称" prop="name" :rules="[{ required: true, message: '请输入角色名称', trigger: 'blur' }]">
          <el-input v-model="formData.name" placeholder="请输入角色名称"></el-input>
        </el-form-item>
        <el-form-item label="角色标识" prop="label" :rules="[{ required: true, message: '请输入角色标识', trigger: 'blur' }]">
          <el-input v-model="formData.label" placeholder="请输入角色标识"></el-input>
        </el-form-item>
        
        <el-form-item label="备注" prop="remark">
          <el-input v-model="formData.remark" type="textarea" placeholder="请输入备注信息" :rows="3"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm" :loading="loading">
          {{ formData.id ? '确定修改' : '确定添加' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.dept-management {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
}

.search-area {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #fff;
  border-radius: 4px;
}

.el-form-item {
  margin-bottom: 0;
}

/* 调整按钮列样式，确保清空按钮到右边框的距离与部门名称到左边框的距离一致 */
.button-col {
  padding-right: 0;
  display: flex;
  justify-content: flex-end;
}

.action-area {
  margin-top: 15px;
}

.pagination-area {
  margin-top: 20px;
  text-align: right;
  width: 100%;
  display: flex;
  justify-content: flex-end;
}

/* 分隔线样式 */
.divider {
  height: 1px;
  background-color: #ebeef5;
  margin: 15px 0;
}

/* 对话框表单样式 */
:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-dialog .el-form-item) {
  margin-bottom: 20px;
}

:deep(.el-input__wrapper) {
  border-radius: 4px;
}

/* 调整选择框样式 */
:deep(.el-dialog .el-select) {
  width: 100%;
}
</style>
